import 'package:get/get_utils/get_utils.dart';
import 'package:largefriends/net/error_handle.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:largefriends/service/im/lf_im_service_send_ext.dart';

import '../../config/lf_im_type.dart';
import '../../entity/entities/chat_new_message_entity.dart';
import '../../entity/entities/lf_message_entity.dart';
import '../../net/lf_api_url.dart';
import 'lf_im_service.dart';

extension IMServiceMSGExt on LfIMService {
  ///先获取内存中的
  List<ChatNewMessageEntity> getMessageListFromMemory(String uid) {
    var result = messageMap[uid];
    if (result == null) {
      result = List.empty(growable: true);
      messageMap[uid] = result;
    }
    return result;
  }

  getMessageListFromNet(
      {required String uid,
      required String lastMessageId,
      required Function() success,
      required Function(int code, String message) error}) async {
    Map<String, dynamic> requestHistoryParam = {};
    var lastHistoryMessageId = lastMessageId;
    // if(messageMap[uid]==null || messageMap[uid]!.isEmpty) {
    //   lastHistoryMessageId = "0";
    // }else {
    //   if(messageLastId[uid] ==null || messageLastId[uid]!.isEmpty){
    //     lastHistoryMessageId = messageMap[uid]!.last.historyId ?? "0";
    //   }
    // }
    requestHistoryParam.putIfAbsent("offset", () => 50);
    requestHistoryParam.putIfAbsent("profId", () => uid);
    requestHistoryParam["messageId"] = lastHistoryMessageId;
    requestHistoryParam["new"] = 0;

    await LfDio()
        .get<List<ChatNewMessageEntity>>(
      url: apiChatHistoryMessages,
      params: requestHistoryParam,
    )
        .then((data) {
      var list = messageMap[uid] ?? List.empty(growable: true);
      if (lastHistoryMessageId == "0") {
        ///相当于refresh
        list.clear();
      }
      list.addAll(data);
      messageMap[uid] = list;
      // if (data.isNotEmpty) {
      //   messageLastId[uid] = data.last.historyId ?? "0";
      // }

      ///获取了新数据就上报
      reportReadTime(uid);
      success.call();
    }, onError: (value) {
      if (value is NetError) {
        error.call(value.code, value.msg);
      }
    });
  }

  receiveAndUpdateMessage(LfMessageEntity responseEntity) {
    if (authService.loggedIn()) {
      var otherUid = '';
      if (authService.currentAccount?.userId == responseEntity.fromUid) {
        otherUid = responseEntity.toUid ?? '';
      } else {
        otherUid = responseEntity.fromUid ?? '';
      }

      if (otherUid.isEmpty) {
        return;
      }
      var entity =
          getMessageListFromMemory(otherUid).firstWhereOrNull((element) {
        return isSameMessageEntity(element, responseEntity);
      });
      if (entity != null) {
        entity
          ..sendState = MessageStatusEnum.success.value
          ..historyId = responseEntity.messageId
          ..duration = responseEntity.duration.toString()
          ..url = responseEntity.url
          ..width = responseEntity.width
          ..height = responseEntity.height
          ..created = responseEntity.time!
          ..messageType = responseEntity.typeId
          ..message = responseEntity.content
          ..replyInfo = responseEntity.replyInfo
          ..roomId = responseEntity.roomId;
      } else {
        ///没有找到,就需要插入数据了,涉及到多端发送
        var conversation = responseEntity.toChatNewMessageEntity(Sender(
            profile: Profile(
                userId: responseEntity.fromUid,
                username: responseEntity.fromName)));
        getMessageListFromMemory(otherUid).insert(0, conversation);
      }
    }
  }

  static int currentTimeMillis() {
    return DateTime.now().millisecondsSinceEpoch ~/
        Duration.microsecondsPerMillisecond;
  }
}
